<template>
    <div class="singer">
      <listview :data1="singers" @select="selectSinger"></listview>
      <router-view></router-view>
    </div>
</template>

<script>
import { getSinger } from '@/api/singer'
import Singer from '../../common/js/singer'
import Listview from '../../base/listview/listview'
import { mapMutations } from 'vuex'

const HOT_NAME = '热门数据'
const HOT_SINGER_LEN = 10

export default {
  name: 'singer',
  components: {Listview},
  data() {
    return {
      singers: []
    }
  },
  mounted () {
    this._getSinger()
  },
  methods: {
    selectSinger(item) {
      this.$router.push({
        path: `/singer/${item.id}`
      })
      this.setSinger(item)
    },
    _getSinger() {
      getSinger().then((res) => {
        if (res.code === 0) {
          this.singers = this._normalizeSinger(res.data.list)
        }
      })
    },
    _normalizeSinger(list) {
      let map = {
        hot: {
          title: HOT_NAME,
          items: []
        }
      }
      list.forEach((item, index) => {
        if (index < HOT_SINGER_LEN) {
          map.hot.items.push(new Singer(
            item.Fsinger_mid,
            item.Fsinger_name))
        }
        const key = item.Findex
        if (!map[key]) {
          map[key] = {
            title: key,
            items: []
          }
        }
        map[key].items.push(
          new Singer(
            item.Fsinger_mid,
            item.Fsinger_name)
        )
      })
      let hot = []
      let ret = []
      for (let key in map) {
        let val = map[key]
        if (val.title.match(/[a-zA-Z]/)) {
          ret.push(val)
        } else if (val.title === HOT_NAME) {
          hot.push(val)
        }
      }
      ret.sort((a, b) => {
        return a.title.charCodeAt(0) - b.title.charCodeAt(0)
      })
      // console.log(hot.concat(ret))
      return hot.concat(ret)
    },
    ...mapMutations({
      setSinger: 'SET_SINGER'
    })
  }
}
</script>

<style lang="stylus" scoped>
  .singer
    position fixed
    top 88px
    bottom 0
    width 100%

</style>
